<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属站点" prop="stationIdC">
        <el-select v-model="queryParams.stationIdC" @change="stationOptionChange" placeholder="请选择站点" clearable filterable>
          <el-option
            v-for="item in stationOptions"
            :key="item.stationIdC"
            :label="item.stationName + ',' + item.stationIdC"
            :value="item.stationIdC">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="历史设备" prop="equipHistoryId">
        <el-select v-model="queryParams.equipHistoryId" placeholder="请选择历史设备" clearable filterable>
          <el-option
            v-for="item in equipHistoryOptions"
            :key="item.equipHistoryId"
            :label="item.equipName"
            :value="item.equipHistoryId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="故障类型" prop="faultTypeId">
        <el-select v-model="queryParams.faultTypeId" placeholder="请选择故障类型" clearable filterable>
          <el-option
            v-for="item in faultTypeOptions"
            :key="item.faultTypeId"
            :label="item.faultTypeName"
            :value="item.faultTypeId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="故障编号" prop="faultCode">
        <el-input
          v-model="queryParams.faultCode"
          placeholder="请输入故障单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="faultStartTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.faultStartTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择故障开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="faultEndTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.faultEndTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择故障结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="故障状态" prop="faultState">
        <el-select v-model="queryParams.faultState" placeholder="请选择故障单状态" clearable size="small">
          <el-option
            v-for="dict in faultStateOptions"
            :key="dict.key"
            :label="dict.value"
            :value="dict.key"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['modules:fault:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['modules:fault:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['modules:fault:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['modules:fault:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="faultList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="故障ID" align="center" prop="faultId" v-if="false"/>
      <el-table-column label="故障单编号" align="center" prop="faultCode" />
      <el-table-column label="所属站点" align="center" prop="stationIdC">
        <template slot-scope="scope">
          <span>{{ stationName(scope.row.stationIdC) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="历史设备" align="center" prop="equipHistoryId" >
        <template slot-scope="scope">
          <span>{{ equipHistoryName(scope.row.equipHistoryId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="故障类型" align="center" prop="faultTypeId" >
        <template slot-scope="scope">
          <span>{{ faultTypeName(scope.row.faultTypeId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理结果" align="center" prop="processResult" />
      <el-table-column label="开始时间" align="center" prop="faultStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.faultStartTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="faultEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.faultEndTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="故障状态" align="center" prop="faultState" >
        <template slot-scope="scope">
          {{ faultStateName(scope.row.faultState) }}
        </template>
      </el-table-column>
      <el-table-column label="上报人" align="center" prop="reportPeopleName" />
      <el-table-column label="上报时间" align="center" prop="reportTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reportTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批人" align="center" prop="approvePeopleName" />
      <el-table-column label="审批时间 " align="center" prop="approveTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['modules:fault:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['modules:fault:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改故障信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-col :span="12">
          <el-form-item label="所属站点" prop="stationId">
            <el-select v-model="form.stationId" placeholder="请选择站点" @change="stationOptionChange" clearable filterable>
              <el-option
                v-for="item in stationOptions"
                :key="item.stationId"
                :label="item.stationName + ',' + item.stationIdC"
                :value="item.stationId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="历史设备" prop="equipHistoryId">
            <el-select v-model="form.equipHistoryId" placeholder="请选择历史设备" clearable filterable>
              <el-option
                v-for="item in equipHistoryOptions"
                :key="item.equipHistoryId"
                :label="item.equipName"
                :value="item.equipHistoryId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="故障类型" prop="faultTypeId">
            <el-select v-model="form.faultTypeId" placeholder="请选择故障类型" clearable filterable>
              <el-option
                v-for="item in faultTypeOptions"
                :key="item.faultTypeId"
                :label="item.faultTypeName"
                :value="item.faultTypeId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="故障单编号" prop="faultCode">
            <el-input v-model="form.faultCode" placeholder="请输入故障单编号" disabled/>
          </el-form-item>
        </el-col>
        <el-form-item label="现场照片">
          <el-upload
            name="files"
            ref="uploadSitePhoto"
            :action="uploadPhotoUrl()"
            :file-list="sitePhotoUrlList"
            :auto-upload="true"
            :before-upload="beforeUploadPhoto"
            :on-remove="removeSitePhoto"
            accept="image/jpg,image/jpeg,image/png"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 jpg/jpeg/png 文件，且不超过 500kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-col :span="24">
          <el-form-item label="处理结果" prop="processResult">
            <el-input v-model="form.processResult" placeholder="请输入处理结果" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="故障开始时间" prop="faultStartTime">
            <el-date-picker clearable size="small"
                            v-model="form.faultStartTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="选择故障开始时间"
                            style="width: 180px">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-form-item label="故障结束时间" prop="faultEndTime">
          <el-date-picker clearable size="small"
                          v-model="form.faultEndTime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择故障结束时间"
                          style="width: 180px">
          </el-date-picker>
        </el-form-item>

        <el-col :span="12">
          <el-form-item label="故障状态" prop="faultState">
            <el-select v-model="form.faultState" placeholder="请选择故障单状态">
              <el-option
                v-for="dict in faultStateOptions"
                :key="dict.key"
                :label="dict.value"
                :value="dict.key"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上报人" prop="reportPeopleName">
            <el-input v-model="form.reportPeopleName" placeholder="请输入上报人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上报人电话" prop="reportPhone">
            <el-input v-model="form.reportPhone" placeholder="请输入上报人联系电话" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上报时间" prop="reportTime">
            <el-date-picker clearable size="small"
                            v-model="form.reportTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="选择上报时间"
                            style="width: 180px">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审批人" prop="approvePeopleName">
            <el-input v-model="form.approvePeopleName" placeholder="请输入审批人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审批时间 " prop="approveTime">
            <el-date-picker clearable size="small"
                            v-model="form.approveTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="选择审批时间 "
                            style="width: 180px">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="22">
          <el-form-item label="备注">
            <editor v-model="form.remark" :min-height="192"/>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listFault, getFault, delFault, addFault, updateFault, exportFault, getFaultCode } from "@/api/modules/fault";
import {listInfoByDto} from "@/api/modules/info";
import { listStationEquipHistoryOption }  from "@/api/modules/equipHistory";
import { listFaultType } from "@/api/modules/faultType";
import Editor from '@/components/Editor';
import { uploadByParent } from "@/api/modules/upload";

export default {
  name: "Fault",
  components: {
    Editor
  },
  data() {
    return {
      // 是否为update
      isUpdate:false,
      // 要删除照片得集合
      deletePhotoList:[],
      // 现场照片集合
      sitePhotoUrlList: [],
      // 故障类型选择列表
      faultTypeOptions:[],
      // 站点所有设备
      allEquipHistory:[],
      // 站点设备选择
      equipHistoryOptions:[],
      // 站点选择列表
      stationOptions:[],
      // 故障状态
      faultStateOptions:[
        {"key":1,value:'未读'},
        {"key":2,value:'已读'},
        {"key":3,value:'已下发'},
        {"key":4,value:'处理中'},
        {"key":5,value:'处理完成'}
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 故障信息表格数据
      faultList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stationIdC: undefined,
        equipHistoryId: undefined,
        faultTypeId: undefined,
        faultCode: undefined,
        faultStartTime: undefined,
        faultEndTime: undefined,
        faultState: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.init();
  },
  methods: {
    /** 获取故障单编号 */
    initFaultCode(){
      getFaultCode().then(res=>{
        this.form.faultCode = res.data.faultCode
      });
    },
    /** 图片移除 */
    removeSitePhoto(file, fileList){
      // 记录删除的照片
      this.deletePhotoList.push(file);
      // 移除
      this.sitePhotoUrlList = fileList
    },
    /** 上传照片前的操作 */
    beforeUploadPhoto(files){
      let formData = new FormData();
      formData.append("files",files);
      uploadByParent(formData,"fault").then(res=>{
        let resList = res.data;
        if(resList){
          this.sitePhotoUrlList = this.sitePhotoUrlList.concat(resList);
        }
      })
    },
    /** 上传照片路径 */
    uploadPhotoUrl(){
      console.log(process.env.VUE_APP_BASE_API + "/uploadByPatent?parent=fault");
      return process.env.VUE_APP_BASE_API + "/uploadByPatent?parent=fault"
    },
    /** 根据站点ID查询历史设备 */
    equipHistoryByStationIdC(stationIdC){
      let selectDto = {
        stationIdC:stationIdC
      };
      listStationEquipHistoryOption(selectDto).then(res=>{
        this.equipHistoryOptions = res.data;
      })
    },
    /** 初始化 */
    init(){
      let selectDto = {
        stationState:1
      };
      let faultType = {
        faultTypeState:0
      }
      listInfoByDto(selectDto).then(res=>{
        this.stationOptions = res.data;
      });
      listFaultType(faultType).then((res=>{
        this.faultTypeOptions = res.rows;
      }))
      listStationEquipHistoryOption().then(res=>{
        this.allEquipHistory = res.data;
        this.equipHistoryOptions = res.data;
      })
    },
    /** 回显故障类型名称 */
    faultTypeName(faultTypeId){
      let value = '';
      this.faultTypeOptions.forEach(faultType =>{
        if(faultType.faultTypeId === faultTypeId){
          value = faultType.faultTypeName;
        }
      });
      return value;
    },
    /** 站点下拉框发生变化时 */
    stationOptionChange(stationIdC){
      // 历史设备发生变化
      this.equipHistoryByStationIdC(stationIdC);
      this.form.equipHistoryId = '';
    },
    /** 回显历史设备名称 */
    equipHistoryName(equipHistoryId){
      let value = '';
      this.equipHistoryOptions.forEach(equipHistory =>{
        if(equipHistory.equipHistoryId === equipHistoryId){
          value = equipHistory.equipName;
          return value;
        }
      });
      return value;
    },
    /** 回显站点名称 */
    stationName(stationIdC){
      let value = '';
      this.stationOptions.forEach(station =>{
        if(station.stationIdC === stationIdC){
          value = station.stationName + "," + station.stationIdC;
          return value;
        }
      });
      return value;
    },
    /** 回显故障状态 */
    faultStateName(key){
      let value = '';
      this.faultStateOptions.forEach(fault =>{
        if(fault.key === key){
          value = fault.value;
        }
      });
      return value;
    },
    /** 查询故障信息列表 */
    getList() {
      this.loading = true;
      listFault(this.queryParams).then(response => {
        this.faultList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.sitePhotoUrlList = [];
      this.deletePhotoList = [];
      this.isUpdate = false;
      this.form = {
        faultId: undefined,
        stationIdC: undefined,
        equipHistoryId: undefined,
        faultTypeId: undefined,
        faultCode: undefined,
        processResult: undefined,
        faultStartTime: undefined,
        faultEndTime: undefined,
        faultState: undefined,
        reportPeopleName: undefined,
        reportPhone: undefined,
        reportTime: undefined,
        approvePeopleName: undefined,
        approveTime: undefined,
        remark: undefined,

      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.faultId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加故障信息";
      // 初始化故障单随机数值
      this.initFaultCode();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isUpdate = true;
      const faultId = row.faultId || this.ids;
      getFault(faultId).then(response => {
        this.sitePhotoUrlList = response.data.tbaseFaultPhotoList;
        this.form = response.data;
        this.open = true;
        this.title = "修改故障信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      // 首先上传图片
      //this.$refs.uploadSitePhoto.submit();
      this.$refs["form"].validate(valid => {
        this.form.sitePhotoUrlList = this.sitePhotoUrlList;
        this.form.deletePhotoList = this.deletePhotoList;
        if (valid) {
          if (this.form.faultId != null) {
            updateFault(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFault(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const faultIds = row.faultId || this.ids;
      this.$confirm('是否确认删除故障信息编号为"' + faultIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delFault(faultIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有故障信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportFault(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
